
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <termios.h>
#include "key.h"

int vm_get_key(void)
{
    struct termios newt, oldt;
    int ch;

    tcgetattr(0, &oldt);
    newt = oldt;
    newt.c_lflag &= ~ICANON;
    newt.c_lflag &= ~ECHO;
    newt.c_cc[VMIN] = 1;
    newt.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &newt);

    ch = getchar();
    tcsetattr(0, TCSANOW, &oldt);
    return ch;
}

int gui_get_key(int *pkey)
{
    int	key;

    // do {
    //     key = getchar();
    //     usleep(20 * 1000);
    // } while (key == X86_KEY_INVALID);
    key = vm_get_key();
    printf("key = %d\n", key);
    fflush(stdout);
    switch(key) {
    case X86_KEY_UP:
        *pkey = GUI_KEY_UP;
        break;
    case X86_KEY_DOWN:
        *pkey = GUI_KEY_DOWN;
        break;
    case X86_KEY_LEFT:
        *pkey = GUI_KEY_LEFT;
        break;
    case X86_KEY_RIGHT:
        *pkey = GUI_KEY_RIGHT;
        break;
    case X86_KEY_ENTER:
        *pkey = GUI_KEY_ENTER;
        break;
    case X86_KEY_ESC:
        *pkey = GUI_KEY_ESC;
        break;
    default:
        *pkey = GUI_KEY_INVALID;
        break;
    }
    return 0;
}
